<template>
  <section v-loading.fullscreen.lock="loading">
    <el-card class="margin-top">
      <div slot="header" class="clearfix relative">
        <el-row>
          <el-col
            :sm="24"
            :md="24"
            :lg="12"
            :xl="12"
            class="flex  align-center justify-start"
          >
            <span class="title-icon margin-right">发货跟踪信息</span>
          </el-col>
          <el-col
            :sm="24"
            :md="24"
            :lg="12"
            :xl="12"
            class="flex  align-center justify-end"
          >
            <el-button
              v-if="isEdit && verifyShow.returnInfoEdit"
              type="success"
              size="mini"
              @click="changeCargoInfo"
            >
              保存仓库地址
            </el-button>
          </el-col>
        </el-row>
      </div>

      <div>
        <hot-table
          ref="hotTable"
          :settings="hotSettings"
          :data="shipmentTrackingInfo"
        />
      </div>
    </el-card>
  </section>
</template>

<script>
import { HotTable } from "@handsontable/vue";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";
import { ajax } from "@/store/yg/common/utils";
import { checkRowsEmpty } from "@/utils";
import "handsontable/languages/zh-CN";
import globalData from "@/utils/config";

export default {
  name: "OrderToOrderToOverseasWarehouseShipping",
  components: {
    HotTable
  },
  props: {
    verifyShow: {
      type: Object,
      default: function() {
        return {};
      }
    },
    shipmentTrackingInfo: {
      type: Array,
      default: function() {
        return [];
      }
    },
    oldShipmentTrackingInfo: {
      type: Array,
      default: function() {
        return [];
      }
    },
    shippingfbastockMap: {
      type: Array,
      default: function() {
        return [];
      }
    },
    actionUrl: {
      type: String,
      default: ""
    },
    waybillId: {
      type: Number,
      default: 1
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      loading: false,
      autoHeight: "auto",
      uploadDialog: false,
      fbaCodeList: []
    };
  },

  watch: {
    shipmentTrackingInfo: {
      handler(newValue, oldValue) {
        if (newValue.length === 0) {
          this.$emit("update:shipmentTrackingInfo", [{}]);
        } else {
          if (this.shippingfbastockMap.length > 0) {
            // this.init();
          } else {
            setTimeout(() => {
              // this.init();
            }, 1000);
          }
        }
        const length = newValue.length;
        if (length < 3) {
          this.autoHeight = "250px";
        } else {
          this.autoHeight = "auto";
        }
      }
      // deep: true,
      // immediate: true
    }
  },
  computed: {
    hotSettings() {
      return {
        rowHeaders: true, // 行表头
        stretchH: "all", // 所有列宽小于表宽时,填充满整个表 all（所有列填充）/last（最后一列）/none(不填充)
        licenseKey: globalData.licensekey,
        // 定义表结构
        colHeaders: ["FBA仓库地址", "派送方式", "追踪号", "快递公司", "备注"],
        width: "100%",
        height: this.autoHeight,

        columns: [
          {
            data: "dispatchAddressCode", //
            width: 100,
            type: "dropdown",
            source: async (query, process) => {
              const s = this.shippingfbastockMap.filter(
                x => x.indexOf(query) > -1
              );
              process(s);
            }
          },
          {
            data: "dispatchWay",
            width: 100,
            type: "dropdown",
            source: ["卡车派送", "快递派送"]
          },
          {
            data: "trackNumber",
            width: 100,
            type: "text"
          },
          {
            data: "expressAddress",
            width: 100,
            type: "text"
          },
          {
            data: "remark",
            width: 100,
            type: "text"
          }
        ],
        tableClassName: ["first-class-name", "second-class-name"],
        language: "zh-CN",
        contextMenu: ["row_above", "row_below", "remove_row", "alignment"], // 开启右键菜单
        beforeRemoveRow: (index, amount, physicalRows, source) => {
          if (this.shipmentTrackingInfo.length === 1) {
            this.shipmentTrackingInfo.push({});
          }
        },
        afterCreateRow: (index, amount, source) => {}
      };
    }
  },

  mounted() {
    // this.init();
    // console.log("this.shippingfbastockMap :>> ", this.shippingfbastockMap);
  },
  methods: {
    async init() {
      for (const i of this.shipmentTrackingInfo) {
        if (i.dispatchAddressCode && i.dispatchAddressCode.indexOf(" ") == -1) {
          const code = i.dispatchAddressCode.slice(
            i.dispatchAddressCode.indexOf("(") + 1,
            i.dispatchAddressCode.length - 1
          );

          const address = this.shippingfbastockMap.find(
            x => x.indexOf(code) > -1
          );
          if (address) {
            this.$delete(i, "dispatchAddressCode");
            this.$set(i, "dispatchAddressCode", address);
          }
        }
      }
    },
    changeCargoInfo() {
      const h = this.shipmentTrackingInfo.filter(x => checkRowsEmpty(x));
      if (h.length === 0) {
        this.$message.error("数据为空！");
        return;
      }
      console.log("h :>> ", h);
      for (const i of h) {
        // if (
        //   i.dispatchAddressCode
        // ) {
        //   this.$message.error("请选择FBA仓库地址");
        //   return;
        // }
        if (
          i.dispatchWay &&
          !["卡车派送", "快递派送"].includes(i.dispatchWay)
        ) {
          this.$message.error("请选择派送方式");
          return;
        }
        if (!i.waybillId) {
          i.waybillId = this.waybillId;
        }
      }
      console.log("h :>> ", h);
      // return
      this.saveInfo(h);
    },
    async saveInfo(h) {
      // 标记已删除数据
      this.loading = true;
      const arr = [];
      for (const i of this.oldShipmentTrackingInfo) {
        const target = h.find(x => x.id === i.id);
        console.log("target :>> ", target);
        if (!target) {
          i.isDel = true;
          arr.push(i);
        }
      }

      const params = [...h, ...arr];
      const { code, message } = await ajax("batchSaveAbroadTrackAddress", {
        abroadTrackAddress: params
      });
      this.loading = false;
      if (code === 200) {
        this.$message({
          type: "success",
          message: "保存成功"
        });
      } else {
        this.$message.error(message);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.relative {
  .absolute {
    right: 10px;
    top: -40%;
  }
}
</style>
<style scoped>
/deep/ .el-card__header {
  padding: 8px 20px;
}
</style>
